package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * author by itheima
 *
 * @Date 2022/3/7
 * Description
 */
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        // 1. 校验 手机号 和 密码是否存在
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if(StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(password)){
            //       先根据手机号 查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"对应用户信息不存在");
            }
            //       判断用户密码是否正确
            String inputPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if(!inputPwd.equals(apUser.getPassword())){
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //       校验用户的状态  true 代表 1
            if (apUser.getStatus()) {
                CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态为锁定状态");
            }
            //       颁发token   用户信息
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            apUser.setPassword("");
            apUser.setSalt("");
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            // 2. 其它情况   判断设备id必须存在
            if(dto.getEquipmentId() == null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"设备id不存在");
            }
            //       直接颁发token   存userId = 0
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
